/**
 * @file 工单列表
 * @author yangjiangming <449654337@qq.com>
 * @date 2018/11/27 10:20:40
 */

layui.define(['element', 'layer', 'form', 'table', 'zmnUtils', 'clipboard', 'previewer', 'oms_work_config', 'list_modify_common','oms_work_modify_route'], function (exports) {
    var $ = layui.$;
    var form = layui.form;
    var element = layui.element;
    var zmnUtils = layui.zmnUtils;
    let layer = layui.layer;
    var clipboard = layui.clipboard;
    var previewer = layui.previewer;
    let table = layui.table;
    let $http = layui.$http;
    var config = layui.oms_work_config;
    var operationList = config.operationList;
    var opCommonUtils = layui.list_modify_common;
    var route = layui.oms_work_modify_route;
    var tabs = [
        { id: -1, name: '全部'  },
        { id: 132, name: '备注' },
        { id: 101, name: '录入' },
        { id: 103, name: '确认' },
        { id: 115, name: '回访' },
        { id: 104, name: '派单' },
        { id: 111, name: '核配件' },
        { id: 113, name: '收单' },
        { id: 114, name: '算账' },
        { id: 108, name: '取消' },
        { id: 105, name: '多工程师' },
        { id: 107, name: '改状态' },
        { id: 117, name: '开发票' },
        { id: 118, name: '推送开票' },
        { id: 200, name: '新跟单' },
        { id: 1000, name: '改派' },
        { id: 1001, name: '取消申请' },
        { id: -3, name: '催单记录' },
        { id: -2, name: '视频' }
    ];

    let POSITION_MAP_URL = '/work/detail/map.action';
    let SHOW_HIDEINFO_URL = '/work/detail/show/hideInfo.action';
    // 优惠信息页面
    var SHOW_DISCOUNT_URL = "/common/select/discount.action";
    // 取消再次上门
    var CANCEL_AGAIN_VISIT = "/work/modify/cancel/multiple/visit.action";
    // 获取优惠页面信息
    var GET_SHOW_DISCOUNT_URL = "/work/detail/getDiscountURL";

    /**
     * 初始化操作记录的 title
     * @param {arrry} tabs 操作列表
     */
    function initTabTitle (tabs) {

        if (cmsVideoRecord == null) {
            tabs.pop();
        }

        var tabsHtmlStr = '';

        tabs.forEach((value, index) => {
            var classArray = [];
            if (index === 0) {
                classArray.push('layui-this');
            }
            tabsHtmlStr += '<li class="'+ classArray.join(' ') +
                '" data-type="' + value.id +
                '" style="padding: 0 5px; ">' + value.name + '</li>';
        });

        $('#log-tab .layui-tab-title').html(tabsHtmlStr);
    }
    /**
     * 刷新详情
     * @param params 参数
     */
    window.reloadDetail = function reloadDetail (params) {
        let defaultParams = zmnUtils.getQueryParams();
        params = Object.assign({}, defaultParams, params);
        opCommonUtils.goSomeWorkDetail(params);
        layer.closeAll();
    };

    function format(date, format) {
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

    // 跳转跟单列表
    function jumpTrackList() {
        var orderId = $('#orderId').val();
        parent.layer.closeAll();
        if (top.isCallCenter) {
            top.layui.index.openTabsPage(config.trackHost + "/track/list.action?orderId=" + orderId, '工单操作：跟单列表');
            return;
        }
        parent.layui.index.openTabsPage(config.trackHost + "/track/list.action?orderId=" + orderId, '跟单列表');
    }

    /**
     * 打开对话框
     * @param {Object} config 配置
     */
    function openDialog (config) {
        let defaultConfig = {
            type: 2,
            content: '/',
            title: '',
            shade: [0.8, '#393D49'],
            area: ['40%', '380px'],
            minWidth: '420px',
            zIndex: layer.zIndex, // 重点1
            success: function(layero) {
                parent.layer.setTop(layero); // 重点2
            },
            end: function(index, layero){
                // 刷新列表
                if(config.reload){
                    table.reload("conf-table", {}, true);
                }
            }
        };
        parent.layer.open(Object.assign({}, defaultConfig, config));
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        element.on("tab(tabChange)", function (e) {
            var type = $(e.elem.context).data('type');

            if (type === -3) {
                var parameter = {
                    "title":"催单记录"
                };
                var workId = $('input[name="workId"]').val();
                var orderId = $('input[name="orderId"]').val();
                let url = route._calculateHostForTRACK() + '/remind/record/list?orderId=' + orderId + '&workId=' + workId;
                zmnLayUtil.openIframeCustom(layer, url, parameter);
                return false;
            }

            if (type === -2) {
                $("#log-tab-div").attr("style", "display:none;");
                $("#video-tab-div").attr("style", "display:block;");
                return;
            }else {
                $("#log-tab-div").attr("style", "display:block;");
                $("#video-tab-div").attr("style", "display:none;");
            }

            var $trList = $('.table-log tbody tr:not(.no-data)');
            var $noData = $('.table-log tbody tr.no-data');

            var $trListOfType = type === -1 ? $trList : $trListOfType = $trList.filter('[data-type="' + type + '"]');

            $('.table-log tbody tr').hide();

            if ($trListOfType.length) {
                $trListOfType.show();
                $noData.hide();
            } else {
                $noData.show();
            }

            // 跟单日志
            /*if (type == 200){
                $trListOfType.show();
                $("#resultEdit").hide();
            } else {
                // 全部隐藏跟单日志
                var $track = $trList.filter('[data-type="200"]');
                $track.hide();
                $("#resultEdit").show();
            }*/
        });

        // 派单快照
        $("a[name='distributeSnapshot']").click(function () {
            var $this = $(this);
            var time = $this.parent().prev().prev().text();
            var year = time.substring(0,2);
            var month = time.substring(3,5);
            var day = time.substring(6,8);
            var hour = time.substring(9,11);
            var minute = time.substring(12,14);
            var second = time.substring(15);

            var snapshotId = year + month + day + hour + minute + second;
            layer.open({
                type: 2,
                title: "派单快照",
                area: ["92%", "425px"],
                fix: true,
                zIndex: 99999999999,
                content: OMS_BASE_URL + "/work/modify/distribute/snapshot.action?workId=" + $("#workId").val() + "&snapshotId=" + snapshotId,
                shade: [0.8, "#393D49"],
                success: function (layero) {

                },
            });
        });

        // 派单快照
        $("span[name='detail-visit']").click(function () {
            var $this = $(this);
            var visitId = $this.data("visit-id");

            layer.open({
                type: 2,
                title: "取消",
                area: ["1150px", "575px"],
                fix: true,
                zIndex: 99999999999,
                content: OMS_BASE_URL + CANCEL_AGAIN_VISIT + "?orderId=" + $('#workId').val() + "&workId=" + $('#orderId').val() + "&visitId=" + visitId,
                shade: [0.8, "#393D49"],
                success: function (layero) {

                },
            })
        });

        // 初始化网络电话组件
        $('body').on('click', '.btn-netcall', function () {
            var masterId = $(this).data('id');
            zmnUtils.makeCall({ masterId: masterId })
        });

        // 显示位置信息
        $('body').on('click', '.zmn-icon-map', function () {

            let orderId = $('input[name=orderId]').val();
            let workId = $('input[name=workId]').val();
            layer.open({
                title: '地图'
                , type: 2
                , area: ['90%', '90vh']
                , fix: true //不固定
                , maxmin: false
                , content: POSITION_MAP_URL + '?orderId=' + orderId + '&workId=' + workId
                , btnAlign: 'c'
            });
        });

        // 查看手机号
        $('.btn-show-phone').on('click', function () {
            let targetId = $(this).data('target');
            let type = $(this).data('type') || 1; // 1：联系电话 2：用户电话 3：用户地址
            let indexPhone = $(this).data('index-phone') || 1; // 第几个号码
            let $targetId = $(targetId);
            let $parent = $(targetId).parent();
            let $copy = $parent.find('.btn-phone-copy');

            $http.get(SHOW_HIDEINFO_URL, {
                orderId: $('#orderId').val(),
                workId: $('#workId').val(),
                moduleId: moduleId,
                type: type,
                index: indexPhone
            }).then(function (data) {
                $targetId.text(data);
                if ($copy && $copy.length > 0) {
                    $copy.data('hidmobile', data);
                }
                $parent.find('a').not('.btn-cc-call').removeClass('layui-hide');
            }, function (msg) {
                layer.msg(msg);
            });
        });

        (function initCallForCC () {
            if (!top.isCallCenter) {
                return;
            }

            $('.btn-cc-call').removeClass('layui-hide');

            // 初始化呼叫电话组件
            $('body').on('click', '.btn-cc-call', function () {
                let telephone = $(this).data('phone');
                if(!telephone) {
                    return;
                }
                let orderId = $('#orderId').val();
                let channelId = $('#channelId').val();
                top.postMessage({
                    type: 2,
                    phone: telephone,
                    bizId: orderId,
                    channelId: channelId,
                    bizType: 'OMS',
                    outBusinessType: 6
                }, '*');
            });
        }());

        // 价格展示页面
        $('.detail-product-price').on('click', function () {
            var parameter = {
                "title":"价格查询"
            };
            var workId = $('input[name="workId"]').val();
            var orderId = $('input[name="orderId"]').val();
            zmnLayUtil.openIframeCustom(layer, OMS_BASE_URL + "/work/price/order/detail.action?orderId="+orderId+"&workId="+workId, parameter);
            return false;
        });

        // 用户档案页面
        $('.detail-userId').on('click', function () {
            var userId = $('span[name="userId"]').text();
            // crm的配置
            var opConfigObj = operationList.find((op) => op.id === 504) || {};
            var userProfile = "/user/info/detail/manager.action";
            var queryParams = {
                userId: userId
            };
            var parameter = {
                "title":"用户档案"
            };
            var url = zmnUtils.serializeURL(opConfigObj.host + userProfile, queryParams);
            zmnLayUtil.openIframeCustom(layer, url, parameter);
            return false;
        });

        // 小区档案页面
        $('.detail-communityId').on('click', function () {
            var communityId = $('#communityId').val();
            var awsProfile = "/community/extra.action";
            var queryParams = {
                communityId: communityId
            };
            var parameter = {
                "title":"小区档案"
            };
            var url = zmnUtils.serializeURL(config.awsHost + awsProfile, queryParams);
            zmnLayUtil.openIframeCustom(layer, url, parameter);
            return false;
        });

        // 跟单列表页面
        $('.detail-distribute-list').on('click', function () {
            if (!isExistTrack) {
                layer.msg('没有跟单记录');
                return false;
            }

            // 无进行中的跟单
            if (!isExistOngoingTrack) {
                layer.open({
                    title: '提示',
                    btn: ['确认', '取消'],
                    content: '无进行中的跟单，是否继续前往查看',
                    yes: function (index, layero) {
                        layer.closeAll();
                        jumpTrackList();
                    },
                    btn2: function (index, layero) {
                        layer.close(index);
                    }
                });
            }else {
                jumpTrackList();
            }
            return false;
        });


        // 分润预估展示页面
        $('.detail-sharing-estimate').on('click', function () {
            var parameter = {
                "title":"分润预估",
                area: ['60%', '70%']
            };
            var workId = $('input[name="workId"]').val();
            var orderId = $('input[name="orderId"]').val();
            zmnLayUtil.openIframeCustom(layer, "/work/erp/sharingestimate.action?orderId="+orderId+"&workId="+workId, parameter);
            return false;
        });

        // 分润预估展示页面
        $('.detail-subworklist').on('click', function () {
            let type = parseInt($(this).data("type"));
            let workNumber = parseInt($(this).data("work-number"));
            let title = '关联工单';

            if(workNumber <= 0 && type === OMS_ORDER_TYPE.ORDER_TYPE_REWORK){
                layer.msg("暂无返修单！");
                return;
            }else if(workNumber <= 0 && type === OMS_ORDER_TYPE.ORDER_TYPE_REFUND){
                layer.msg("暂无退款单！");
                return;
            }else if(workNumber <= 0 && type === OMS_ORDER_TYPE.ORDER_TYPE_COMPENSATE){
                layer.msg("暂无赔偿单！");
                return;
            }

            switch (type) {
                case OMS_ORDER_TYPE.ORDER_TYPE_NEW:
                    title = '新单';
                    break;
                case OMS_ORDER_TYPE.ORDER_TYPE_REWORK:
                    title = '返修单';
                    break;
                case OMS_ORDER_TYPE.ORDER_TYPE_REFUND:
                    title = '退款单';
                    break;
                case OMS_ORDER_TYPE.ORDER_TYPE_COMPENSATE:
                    title = '赔偿单';
                    break;
                default:
                    break;
            }



            var parameter = {
                "title": title,
                area: ['60%', '70%']
            };

            let originalId = $(this).data("original-id");
            let userId = $(this).data("user-id");

            let url = "/work/detail/subworklist.action?type=" + type;
            if (originalId) {
                url = url + "&originalId=" + originalId;
            }
            if (userId) {
                url = url + "&userId=" + userId;
            }

            zmnLayUtil.openIframeCustom(layer, url, parameter);
            return false;
        });

        // 优惠分摊展示页面
        $('.detail-sharing-discount').on('click', function () {
            var parameter = {
                "title":"优惠分摊规则",
                area: ['30%', '20%'],
                shade: [0.1, '#fff'],
                shadeClose: true
            };
            let categ = $(this).data("categ") | 0;
            let sourceId = $(this).data("sourceid") | 0;
            zmnLayUtil.openIframeCustom(layer, "/work/detail/discountsharing.action?categ=" + categ + "&sourceId=" + sourceId, parameter);
            return false;
        });

        // 点击查看打开渠道邀评说明
        $('.channel-order-conf-detail-invite').on('click', function () {
            openDialog({
                type: 1,
                shade: 0.8,
                offset: 'auto',
                area: [600 + 'px',300+'px'],
                shadeClose:true,
                scrollbar: false,
                title: "邀评说明", //不显示标题
                content: detailVo.inviteCommentExplain, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
                reload:false
            })
        });

        // 点击查看打开尾款支付说明
        $('.channel-order-conf-detail-pay').on('click', function () {
            openDialog({
                type: 1,
                shade: 0.8,
                offset: 'auto',
                area: [600 + 'px',300+'px'],
                shadeClose:true,
                scrollbar: false,
                title: "尾款支付说明", //不显示标题
                content: detailVo.finalPayExplain,
                reload:false
            })
            return false;
        });

        // 查看快递
        $('.detail-express').on('click', function () {
            var express = $(this).data('express');
            var html = '';
            if (express && express.length > 0) {
                express.forEach(function ({date, content}, index) {
                    html += '<div style="padding: 8px 0">' + content + '<br/>' + format(new Date(date), 'yyyy-MM-dd hh:mm:ss') + '</div>';
                });
            }
            if (html == '') {
                html = '没有查询到物流信息';
            }

            layer.open({
                type: 1
                , area: ['500px', '400px']
                , title: ' 物流追踪'
                , content: '<div style="padding: 20px;color: #666666;">' + html + '</div>'
                , btnAlign: 'c'
            });
            return false;
        });

        $('.v-player').each(function(){ //遍历视频列表
            // $(this).hover(function(){ //鼠标移上来后显示播放按钮
            //     $(this).find('.videoed').show();
            // },function(){
            //     $(this).find('.videoed').hide();
            // });
            $(this).click(function(){ //这个视频被点击后执行
                var img = $(this).attr('vpath');//获取视频预览图
                var video = $(this).attr('ipath');//获取视频路径
                $('.videos').html("<video id=\"video\" poster='"+img+"' src='"+video+"' preload=\"auto\" controls=\"controls\" autoplay=\"autoplay\"></video><i class=\"vclose layui-icon layui-icon-close-fill\"></i>");
                $('.videos').show();
            });
        });

        $(document).on('click', '.vclose', function () {
            //点击关闭按钮关闭暂停视频
            $('.videos').hide();
            v.pause();
            $('.videos').html('');
        })

        /**
         * 优惠信息查询事件
         */
        $("#selectDiscount").click(function () {
            var orderId = $('#orderId').val();
            var workId = $('#workId').val();

            $http
                .$get(GET_SHOW_DISCOUNT_URL, {
                    orderId: orderId,
                    workId: workId
                })
                .then(
                    function (data) {
                        // 打开弹窗
                        layer.open({
                            type: 2,
                            title: "优惠信息查询",
                            area: ["1350px", "675px"],
                            fix: true,
                            zIndex: 99999999999,
                            content: SYS_BASE_URL_ENUM.dms + data,
                            shade: [0.8, "#393D49"],
                            success: function (layero) {
                                // window.showDiscountOptions = {
                                //     showDiscountDTO: showDiscountDTO
                                // };
                            },
                        })
                    },
                    function (msg) {
                        layer.msg(msg);
                    }
                );
        });
    }

    /**
     * 更多
     */
    function initModal() {
        $('[data-toggle="modal"]').on('click', function(){
            var that = $(this);
            var targetId = that.data('target');
            if(!targetId){
                return false;
            }
            var mobile = $(that.data('phone-target')).text();

            var idxLayer = layer.open({
                type: 1,
                title: '发短信',
                skin: 'modal', //样式类名
                btnAlign: 'c',
                closeBtn: 1,
                anim: -1,
                area: ['600px', '320px'],
                content: $(targetId).html(),
                success: function ($layer, index) {
                    $layer.find('.submit-btn').attr('lay-filter', 'form-submit');
                    $layer.find('.cancel-btn').attr('lay-filter', 'form-cancel');
                    $layer.find('[name=mobile]').val(mobile);

                    // 根据渠道处理短信模板内容
                    var channelId = $('#channelId').val();

                    var $select = $layer.find('select');
                    var channelGroupHtml = '';
                    $select.find('option').each(function () {
                        var channelIds = $(this).data('channelids');
                        if (channelIds && channelIds.indexOf(channelId + ',') > -1) {
                            channelGroupHtml = $(this).prop("outerHTML");;
                        }
                    })
                    if (channelGroupHtml) {
                        $select.html(channelGroupHtml);
                    } else {
                       // 删除特殊渠道模板选项
                        $select.find('option').each(function () {
                            var channelIds = $(this).data('channelids');
                            if (channelIds) {
                                $(this).remove();
                            }
                        })
                    }

                    // 默认选项第一个
                    $layer.find('.layui-textarea').text($layer.find('option:first').data('content'));

                    form.render('select');

                    form.on('select(groupId)', function (data) {
                        var content = $(data.elem).find('option:selected').data('content');
                        $layer.find('.layui-textarea').text(content || '');
                    });

                    form.on('submit(form-submit)', function (data) {
                        data.field.orderId = $('#orderId').val();
                        data.field.workId = $('#workId').val();
                        data.field.moduleId = moduleId;
                        $http.lockSave('/work/modify/send/sms.action', data.field, data.elem).then(function () {
                            layer.close(idxLayer);
                            zmnUtils.layui.toastSuccess('短信发送成功');
                        }, function (msg) {
                            layer.msg(msg);
                        });
                        return false;
                    });

                    form.on('submit(form-cancel)', function () {
                        layer.close(idxLayer);
                        return false;
                    });
                }
            });

            return false;
        });
    }


    /**
     * 初始化页面
     */
    function initPage () {
        // 初始化剪切板控制器
        clipboard.init();

        // 初始化剪切板控制器
        let $clipboard = new ClipboardJS('.btn-phone-copy', {
            text: function (trigger) {
                let $trigger = $(trigger);
                let hidMobile = $trigger.data('hidmobile')+'';
                let cryptoMobile = $trigger.data('cryptomobile');
                if (hidMobile.indexOf("**") > 0) {
                    return '{"show":"' + hidMobile + '","ciphertext":"' + cryptoMobile + '"}';
                } else {
                    return hidMobile;
                }
            }
        });

        $clipboard.on('success', function(e) {
            layer.tips('复制成功', e.trigger, {
                time: 500,
                tips: [3, '#5FB878']
            })
        });

        initTabTitle(tabs);

        // // 初始化图片预览器
        previewer.initTextList('.container-images');



        initModal();

        // 初始化页面数据
        initEvent();
    }

    initPage();
    exports('oms_work_detail');
});
